package com.bdqn.ch01.SZ.sz3;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * MethodTest
 *
 * @aurhor Administrator  whs
 * @since 2024/7/1
 */
public class MethodTest {
    public static void main(String[] args) {
        try {
            // 通过反射加载 Person 的方法
            Class clz = Class.forName("com.bdqn.ch01.Sl.Person");

            // 根据方法名和参数列表获取 static final int getAge 方法
            Method getAge = clz.getDeclaredMethod("getAge",null);

            //  getAge  的方法 default(package) , 这里已经超出其访问范围 ，不能直接访问
            // 通过 setAccessible 方法 可以访问到
            getAge.setAccessible(true);
            Object returnAge = getAge.invoke(null,null);
            System.out.println("年龄是：" + returnAge);

            // 创建Person实例
            Object person = clz.newInstance();

            Method silentMethod = clz.getDeclaredMethod("silentMethod",null);
            silentMethod.setAccessible(true);
            silentMethod.invoke(person,null);

            Method setName = clz.getDeclaredMethod("setName", String.class);
            setName.invoke(person,"曹嫩猪好帅~~");
            Object returnName = clz.getDeclaredMethod("getName").invoke(person);
            System.out.println("\n刚才设定的name是："+returnName);


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
